package com.hjx.system;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class NashornUtil {

    private static final ScriptEngineManager sm = new ScriptEngineManager();

    private static final ScriptEngine nashorn;
    private static Bindings finalBindings;
    static {
        nashorn = sm.getEngineByName("js");

        try {
            nashorn.eval("load('js/common/util.js')");
            nashorn.eval("load('js/common/imports.js')");

            Bindings bindings = nashorn.createBindings();
            // bindings.putAll((Bindings) nashorn.eval("this"));
            finalBindings =  (Bindings) nashorn.eval("_G");

        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }


    public static ScriptEngine getScriptEngine(){
        return nashorn;
    }

    public static Bindings getFinalBindings() {
        return finalBindings;
    }

    public static void syncImportsToScriptContext(ScriptContext scriptContext) throws ScriptException {
        Bindings bindings = nashorn.createBindings();
        bindings.putAll(NashornUtil.getFinalBindings());


        //为线程独享Bindings绑定参数
        scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        scriptContext.setAttribute("_G", bindings, ScriptContext.ENGINE_SCOPE);

    }

    public static <T> T getVariableFromScriptContext(String variableName, ScriptContext scriptContext, Class<T> clazz) throws ScriptException {
        return (T)nashorn.eval(variableName, scriptContext);
    }
}
